package com.delayqueue.core.permanent;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.FileOutputStream;
import java.io.IOException;

@Slf4j
@Component
@Getter
@Setter
public class PermanentStream implements DisposableBean {

    @Autowired
    private PermanentConfig permanentConfig;
    @Autowired
    private PermanentFile permanentFile;
    private FileOutputStream taskWriter;
    private FileOutputStream completedWriter;
    private FileOutputStream taskTempWriter;
    private FileOutputStream completedTempWriter;


    protected synchronized void openDatStream() {
        try {
            if (taskWriter == null) {
                taskWriter = new FileOutputStream(permanentFile.getTaskDataFile(), true);
            }
            if (completedWriter == null) {
                completedWriter = new FileOutputStream(permanentFile.getCompletedDataFile(), true);
            }
            releaseTempStream();
        } catch (IOException e) {
            log.error("出错了：", e);
        }
    }


    protected synchronized void openTempStream() {
        try {
            if (taskTempWriter == null) {
                taskTempWriter = new FileOutputStream(permanentFile.getTaskTempFile(), true);
            }
            if (completedTempWriter == null) {
                completedTempWriter = new FileOutputStream(permanentFile.getCompletedTempFile(), true);
            }
        } catch (IOException e) {
            log.error("出错了：", e);
        }
    }

    protected void releaseTempStream() {
        try {
            if (taskTempWriter != null) {
                taskTempWriter.flush();
                taskTempWriter.close();
                taskTempWriter = null;
            }
            if (completedTempWriter != null) {
                completedTempWriter.flush();
                completedTempWriter.close();
                completedTempWriter = null;
            }
        } catch (IOException e) {
            log.error("出错了：", e);
        }
    }

    @Override
    public void destroy() throws IOException {

        if (taskWriter != null) {
            taskWriter.flush();
            taskWriter.close();
            taskWriter = null;
        }
        if (completedWriter != null) {
            completedWriter.flush();
            completedWriter.close();
            completedWriter = null;
        }
        releaseTempStream();
    }
}
